#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <iconv.h>

#define UNIT_TEST 0

static int32_t CodeConvert(const char *from_charset,const char *to_charset, char *inbuf, int32_t inlen, char *outbuf, int32_t outlen)                        
{
    iconv_t   cd;
    char **pin  = &inbuf;     
    char **pout = &outbuf;    
    char *out = outbuf;
    int len = outlen;
    int i;
    char tmp;

    cd = iconv_open(to_charset,from_charset);
    if(cd==0)
    {
        printf("iconv_open error!\n");
        return   -1;          
    }

    memset(outbuf,0,outlen);  

    if(iconv(cd, pin,   (size_t*)&inlen,   pout,   (size_t*)&outlen)==(size_t)-1) 
    {
        if(E2BIG == errno)
        {
            printf("out buffer over!");
        }
        else if(EINVAL == errno)
        {
            printf("An incomplete multibyte sequence is encountered!\n");
        }
        else if(EILSEQ == errno)
        {
            printf("An invalid multibyte sequence is encountered!\n");
        }
        return   -1;
    }
    iconv_close(cd);

    len = len - outlen;

    if(!strcmp(from_charset, "utf-8") && !strcmp(to_charset, "utf-16"))
    {
        /* switch byte order */
        for(i=0; i<len; i+=2)
        {
            tmp = out[i];
            out[i] = out[i+1];
            out[i+1] = tmp;
        }
    }

    return len;
}

int32_t Utf8ToUtf16(char *in, int32_t inlen, char *out, int32_t outlen)
{
    return CodeConvert("utf-8", "utf-16", in, inlen, out, outlen);
}

int32_t Utf16ToUtf8(char *in, int32_t inlen, char *out, int32_t outlen)
{
    int ret = 0;
    char *p = (char *)malloc(inlen+4);

    if(p!=NULL)
    {
        memset(p, 0, inlen+4);
        p[0] = 0xfe;
        p[1] = 0xff;
        memcpy(p+2, in, inlen);
        ret = CodeConvert("utf-16", "utf-8", p, inlen+2, out, outlen);
        free(p);
    }
    else
    {
        ret = 0;
    }

    return ret;
}
#if UNIT_TEST
int main(int argc, char *argv[])
{
    int inlen;
    int outlen;
    char text[] = "123模块查询，设备查询\n";
    char text2[] = {0xfe, 0xff, 0x62, 0x11, 0x66, 0x2f, 0x8c, 0x01, 0xff, 0x01, 00};/*我是谁！*/
    char out[128];

    memset(out, 0, sizeof(out));

    inlen = strlen(text);
    outlen = 128;



    outlen = Utf8ToUtf16(text, inlen, out, outlen);
    printf("%s", text);
    
    printf("outlen is %d\n", outlen);

    for(inlen=0; inlen < outlen; inlen+=2)
    {
        printf("%02x%02x\n", (unsigned char)out[inlen], (unsigned char)out[inlen+1]);
    }

    inlen = sizeof(text2) - 1;
    outlen = 128;

    outlen = Utf16ToUtf8(text2, inlen, out, outlen);
    printf("outlen is %d\n", outlen);
    printf("%s\n", out);

    return 0;
    
}

#endif
